package com.ocom.exposeapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.constant.ExposeApiUrl;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.emqx.DoorResponse;
import com.ocom.common.request.emqx.FyRequest;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.accessdevice.RegionAreaInfo;
import com.ocom.common.vo.recode.DoorRecodeVo;
import com.ocom.exposeapi.feign.*;
import com.ocom.exposeapi.vo.JKMVo;
import com.ocom.exposeapi.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

@Slf4j
@RestController
public class EmqxController {


	private static final Logger logger = LoggerFactory.getLogger(EmqxController.class);

	@Autowired
	AccessService accessService;

	@Autowired
	EmqxClientService emqxClientService;

	@Autowired
	CompanyClientService companyClientService;

	@Autowired
	private HumanFeignService humanFeignService;

	@Autowired
	private SrvpaccessClientService srvpaccessClientService;

	@Autowired
	private MjrecodeClientService mjrecodeClientService;

	@Autowired
	WebSocketApiClientService webSocketApiClientService;


	@PostMapping(ExposeApiUrl.URL_ExposeApi_FangYi)
	public JKMVo fangyi(@RequestBody FyRequest fyRequest){
		/**
		 * 	Integer comid;
		 * 	String nonceStr;
		 * 	String sign;
		 * 	Integer type;
		 * 	String param;
		 * 	String transferId;
		 */

		JKMVo jkmVo=new JKMVo();
		jkmVo.setCode(4001);
		jkmVo.setType(fyRequest.getType());
		jkmVo.setMessage("fail");
		jkmVo.setData(null);
		jkmVo.setTransferId(fyRequest.getTransferId());
		jkmVo.setTimestamp(System.currentTimeMillis());

		return jkmVo;
/**
		if(fyRequest.getComid()==null || fyRequest.getComid()<=0){
			jkmVo.setCode(4001);
			jkmVo.setMessage("comid 不能为空");
			return jkmVo;
		//	return DoorResponse.error(4001,"comid 不能为空",fyRequest.getTransferId());
		}
		if(CommonUtil.isNull(fyRequest.getNonceStr())){
			jkmVo.setCode(4001);
			jkmVo.setMessage("nonceStr 不能为空");
			return jkmVo;
	//		return DoorResponse.error(4001,"nonceStr 不能为空",fyRequest.getTransferId());
		}
		if(fyRequest.getNonceStr().length()<32 || fyRequest.getNonceStr().length()>50){
			jkmVo.setCode(4001);
			jkmVo.setMessage("nonceStr 长度32-50");
			return jkmVo;
	//		return DoorResponse.error(4001,"nonceStr 长度32-50",fyRequest.getTransferId());
		}

		if(CommonUtil.isNull(fyRequest.getSign())){
			jkmVo.setCode(4001);
			jkmVo.setMessage("sign 不能为空");
			return jkmVo;
//			return DoorResponse.error(4001,"sign 不能为空",fyRequest.getTransferId());
		}
		if(fyRequest.getType()==null){
			jkmVo.setCode(4001);
			jkmVo.setMessage("type 不能为空");
			return jkmVo;
	//		return DoorResponse.error(4001,"type 不能为空",fyRequest.getTransferId());
		}
		if(CommonUtil.isNull(fyRequest.getParam())){
			jkmVo.setCode(4001);
			jkmVo.setMessage("param 不能为空");
			return jkmVo;
		//	return DoorResponse.error(4001,"param 不能为空",fyRequest.getTransferId());
		}
		if(CommonUtil.isNull(fyRequest.getTransferId())){
			jkmVo.setCode(4001);
			jkmVo.setMessage("transferId 不能为空");
			return jkmVo;
	//		return DoorResponse.error(4001,"transferId 不能为空",fyRequest.getTransferId());
		}
		if(fyRequest.getTransferId().length()<32 || fyRequest.getTransferId().length()>50){
			jkmVo.setCode(4001);
			jkmVo.setMessage("transferId 长度32-50");
			return jkmVo;
		//	return DoorResponse.error(4001,"transferId 长度32-50",fyRequest.getTransferId());
		}
		if(fyRequest.getTimestamp()==null || fyRequest.getTimestamp()<=0l){
			jkmVo.setCode(4001);
			jkmVo.setMessage("timestamp 不能为空");
			return jkmVo;
		//	return DoorResponse.error(4001,"timestamp 不能为空",fyRequest.getTransferId());
		}

		Result result=companyClientService.getCompanyKeyInfoOne(fyRequest.getComid().longValue());
		if(result.getCode()!=200){
			jkmVo.setCode(4002);
			jkmVo.setMessage("单位未配置密钥");
			return jkmVo;
		}

		JSONObject jsonObject= JSON.parseObject(JSON.toJSONString(result.getData()));

		if(!jsonObject.containsKey("commKey")){
			jkmVo.setCode(4002);
			jkmVo.setMessage("单位未配置密钥#");
			return jkmVo;
		}

		String commKey=jsonObject.getString("commKey");

		Gson gson=new Gson();

		//身份证效验
		if(fyRequest.getType()==1){

			if(CommonUtil.isNull(fyRequest.getName())){
				jkmVo.setCode(4001);
				jkmVo.setMessage("name 不能为空#");
				return jkmVo;
			}

			try {
				String secret= commKey;
				String md5 = MD5.MD5Encode(secret,"utf8");
				String key= md5.substring(0,16);

				String cipherTextIdentity = AES.PKCS5Decrypt(fyRequest.getParam(),key);
				String cipherTextName = AES.PKCS5Decrypt(fyRequest.getName(),key);

				if(CommonUtil.isNull(cipherTextIdentity) || CommonUtil.isNull(cipherTextName) ){
					jkmVo.setCode(4003);
					jkmVo.setMessage("身份证姓名解析失败");
					return jkmVo;
				}
				fyRequest.setParam(cipherTextIdentity);
				fyRequest.setName(cipherTextName);

			}catch (Exception e){
				jkmVo.setCode(4003);
				jkmVo.setMessage("身份证姓名解析失败#");
				return jkmVo;
			}
			boolean bp= IdentificationCodeUtil.isIdentityCode(fyRequest.getParam());
			if(!bp){
				jkmVo.setCode(4001);
				jkmVo.setMessage("身份证不符合#");
				return jkmVo;
				//	return DoorResponse.error(4001,"身份证不符合",fyRequest.getTransferId());
			}
		}else{
			try {
				Map<String,Object> objectMap=gson.fromJson(fyRequest.getParam(),Map.class);
				if(!objectMap.containsKey("codeId") && !objectMap.containsKey("encode")){
					jkmVo.setCode(4001);
					jkmVo.setMessage("健康码异常解析异常");
					return jkmVo;
					//		return DoorResponse.error(4001,"请检查数据格式",fyRequest.getTransferId());
				}
			}catch (Exception e){
				jkmVo.setCode(4001);
				jkmVo.setMessage("健康码异常解析异常#");
				return jkmVo;
				//	return DoorResponse.error(4001,"请检查数据格式",fyRequest.getTransferId());
			}
		}

		SortedMap<String,Object> sortedMap = new TreeMap<String,Object>();
		sortedMap.put("comid",fyRequest.getComid());
		sortedMap.put("nonceStr",fyRequest.getNonceStr());
		sortedMap.put("type",fyRequest.getType());
		sortedMap.put("param",fyRequest.getParam());
		sortedMap.put("transferId",fyRequest.getTransferId());
		sortedMap.put("timestamp",fyRequest.getTimestamp());
		sortedMap.put("name",fyRequest.getName());
		String sign= SignUtils.createSign(sortedMap,commKey);

		if(!sign.equals(fyRequest.getSign())){
			log.info("签名不匹配 sortedMap【{}】commKey【{}】sign【{}】fyRequest【{}】",sortedMap ,commKey ,sign ,fyRequest);
			jkmVo.setCode(4004);
			jkmVo.setMessage("签名异常#");
			return jkmVo;
//			return DoorResponse.error(4002,"签名异常",fyRequest.getTransferId());
		}

		Result fangyi = commonHandleWay(fyRequest);

		jkmVo.setCode(fangyi.getCode());
		jkmVo.setData(null);
		jkmVo.setTimestamp(System.currentTimeMillis());
		jkmVo.setMessage(fangyi.getMsg());
		if(fangyi.getCode()==200){
			jkmVo.setData(fangyi.getData());
		}
		return jkmVo;


 **/
	}

	@PostMapping(ExposeApiUrl.URL_InsideApi_FangYi)
	public Result insideFangYi(Integer type ,Integer  companyId,String identity, String name){
		return ResultUtil.error(ResultEnum.Err_900);

//		FyRequest fyRequest=new FyRequest();
//		fyRequest.setComid(companyId);
//		fyRequest.setType(type);
//		fyRequest.setParam(identity);
//		fyRequest.setName(name);
//		fyRequest.setNonceStr(RandomUtil.getRandomString(32));
//		fyRequest.setTransferId(RandomUtil.getRandomString(32));
//		fyRequest.setTimestamp(System.currentTimeMillis());
//		return  commonHandleWay(fyRequest);
	}

	public Result commonHandleWay(FyRequest fyRequest){
		//判断是否有中育
		if(fyRequest.getType()==1){
			Result result1=accessService.getZyResult(fyRequest.getComid().longValue(),fyRequest.getParam(),fyRequest.getName());
			if(result1.getCode()==200){
				return ResultUtil.success(result1.getData());
			}
		}
		return emqxClientService.fangyi(fyRequest);
	}


	@PostMapping(ExposeApiUrl.URL_ExposeApi_GetLock)
	public DoorResponse getAroundLock(String message,String machNo, String sign){

		return DoorResponse.error("error","000");
//		return  emqxClientService.getAroundLock(message,machNo,sign);
	}


	@PostMapping(ExposeApiUrl.URL_SaveDoorRecords)
	public ResultVo saveDoorRecords(@RequestBody JSONObject jsonObject){
		ResultVo resultVo=new ResultVo();
		if (!StringUtils.isEmpty(jsonObject.getString("transferId"))){
			resultVo.setTransferId(jsonObject.getString("transferId"));
		}
		try {
			log.info("请求方式:【{}】,请求参数:【{}】","3.1.保存开门记录",jsonObject);

			if (StringUtils.isEmpty(jsonObject.getString("nonceStr")) || StringUtils.isEmpty(jsonObject.getString("sign"))
					|| jsonObject.getLong("comId")==null){
				resultVo.setCode(203);
				resultVo.setMessage("必填参数值为空");
				return resultVo;
			}
			if (jsonObject.getLong("timestamp")==null
					|| jsonObject.get("param")==null){
				resultVo.setCode(203);
				resultVo.setMessage("必填参数值为空");

				return resultVo;
			}
			JSONObject param=JSON.parseObject(JSON.toJSONString(jsonObject.get("param")));
			if (StringUtils.isEmpty(param.getString("pCode"))){
				resultVo.setCode(203);
				resultVo.setMessage("学号不能为空");
				return resultVo;
			}

			if (StringUtils.isEmpty(param.getString("pName"))){
				resultVo.setCode(203);
				resultVo.setMessage("姓名不能为空");
				return resultVo;
			}

			if (param.get("openTime")==null){
				resultVo.setCode(203);
				resultVo.setMessage("识别时间不能为空");
				return resultVo;
			}

			if (param.get("openType")==null){
				resultVo.setCode(203);
				resultVo.setMessage("开门方式不能为空");
				return resultVo;
			}

			if (StringUtils.isEmpty(param.get("deviceNo"))){
				resultVo.setCode(203);
				resultVo.setMessage("识别设备序列号不能为空");
				return resultVo;
			}

		/*	if (StringUtils.isEmpty(param.getString("regionName"))){
				resultVo.setCode(203);
				resultVo.setMessage("设备归属校区名称不能为空");
				return resultVo;
			}*/

			Result result=companyClientService.getCompanyKeyInfoOne(jsonObject.getLong("comId"));
			if(result.getCode()!=200){
				resultVo.setCode(4002);
				resultVo.setMessage("单位未配置密钥");
				return resultVo;
			}

			JSONObject keyObject= JSON.parseObject(JSON.toJSONString(result.getData()));

			String commKey=keyObject.getString("commKey");

			SortedMap<String,Object> sortedMap = new TreeMap<String,Object>();
			sortedMap.put("comid",jsonObject.getLong("comId"));
			sortedMap.put("nonceStr",jsonObject.getString("nonceStr"));
			sortedMap.put("param",jsonObject.getString("param"));
			sortedMap.put("transferId",jsonObject.getString("transferId"));
			sortedMap.put("timestamp",jsonObject.getLong("timestamp"));
			String sign= SignUtils.createSign(sortedMap,commKey);
			if(!sign.equals(jsonObject.getString("sign"))){
				resultVo.setCode(4004);
				resultVo.setMessage("签名错误#");
				return resultVo;
			}

			//判断设备是否存在
			Result result1 = accessService.getMachineInfoById(jsonObject.getLong("comId"),param.getString("deviceNo"));
			if(result1.getCode()!=200){
				resultVo.setCode(4005);
				resultVo.setMessage("设备未登记#");
				log.info("设备【{}】未登记,参数【{】】",param,jsonObject.getLong("comId"));
				return resultVo;
			}


			JSONObject personnel=new JSONObject();
			personnel.put("comId",jsonObject.getLong("comId"));
			personnel.put("pCode",param.getString("pCode"));
			personnel.put("pName",param.getString("pName"));
			personnel.put("status",0);
			personnel.put("page",1);
			personnel.put("size",1);
			Result personnelGetStudentResult=humanFeignService.PersonnelGetStudentInfo(personnel);
			Long pId=0l;
			Integer pType=0;
			String deptName="";
			Long deptId=0l;
			if (personnelGetStudentResult.getCode()==200){
				try{
					JSONObject studentJSON =JSON.parseObject(JSON.toJSONString(personnelGetStudentResult.getData()));
					List<JSONObject> studentList=JSON.parseArray(JSON.toJSONString(studentJSON.get("list")),JSONObject.class);
					if (studentList.size()>0){
						for (JSONObject object : studentList) {
							pId=object.getLong("pId");
							pType=object.getInteger("pType");
							deptId=object.getLong("deptId");
							deptName=object.getString("deptName");
						}
					}
				}catch (Exception e){
					log.info("请求方式:【{}】,请求参数:【{}】,返回参数:【{}】,异常:【{}】","未找到学生",personnel,personnelGetStudentResult,e);
				}
			}

			int openType=0;
			if (param.getInteger("openType")==1 || param.getInteger("openType")==3){
				openType=1;
			}else if (param.getInteger("openType")==0 || param.getInteger("openType")==2){
				openType=0;
			}
			DoorRecodeVo recodeVo=new DoorRecodeVo();
			recodeVo.setDeptName(deptName);
			recodeVo.setDeptId(deptId.intValue());
			recodeVo.setComId(jsonObject.getInteger("comId"));
			recodeVo.setDeviceNo(param.getString("deviceNo"));
			recodeVo.setOpenTime(DateUtils.getStrDate(param.getDate("openTime"),DateUtils.YYYY_MM_DD_HH_MM_SS));
			recodeVo.setOpenMode(4);
			recodeVo.setOpenType(openType);
			recodeVo.setPId(Math.toIntExact(pId));
			recodeVo.setPCode(param.getString("pCode"));
			recodeVo.setPName(param.getString("pName"));


			RespMachMessage reginIdResult=srvpaccessClientService.getReginIdByMach(jsonObject.getLong("comId"),param.getString("deviceNo"));
			if (!reginIdResult.getCode().equals("0000")){
				resultVo.setCode(4005);
				resultVo.setMessage("上传门禁记录失败");
				log.info("请求方式:【{}】,请求参数:【{}】,返回参数:【{}】","上传门禁记录失败",jsonObject,reginIdResult);
				return resultVo;
			}

			JSONObject reginIdJSONObject=JSON.parseObject(JSON.toJSONString(reginIdResult.getData()));
			Long reginId=reginIdJSONObject.getLong("regionId");
			recodeVo.setRecodeId(RandomUtil.getRandomString(30));

			try {
				Gson gson = new Gson();
				Result resultAccess = accessService.getAreaInfoByMachNo(recodeVo.getComId().longValue(), recodeVo.getDeviceNo());
				RegionAreaInfo regionAreaInfo = gson.fromJson(gson.toJson(resultAccess.getData()), RegionAreaInfo.class);
				if (resultAccess.getCode() == 200) {
					recodeVo.setAreaId(regionAreaInfo.getAreaId());
					recodeVo.setAreaName(regionAreaInfo.getAreaName());
					recodeVo.setRegionId(regionAreaInfo.getRegionId());
					recodeVo.setRegionName(regionAreaInfo.getRegionName());
				}
			}catch (Exception e){
				log.info("异常:【{}】","匹配校区和区域",e);
			}

			recodeVo.setPType(pType);
			Result saveAccessResult=mjrecodeClientService.saveAccessRecord(recodeVo);
			if (saveAccessResult.getCode()!=200){
				resultVo.setCode(4005);
				resultVo.setMessage("上传门禁记录失败");
				log.info("请求方式:【{}】,请求参数:【{}】,返回参数:【{}】","上传门禁记录失败",jsonObject,saveAccessResult);
				return resultVo;
			}

			try{
				if(!CommonUtil.isNull(recodeVo.getPName())){
					recodeVo.setPName(com.ocom.common.utils.StringUtils.desValue(recodeVo.getPName(),1,1,"*"));
				}
				webSocketApiClientService.webSocketMsg(recodeVo);
			}catch (Exception e){
				log.info("请求参数:【{}】,返回参数:【{}】,异常:【{}】","发送websocket",recodeVo,personnelGetStudentResult,e);
			}

			JSONObject updatePersonnel=new JSONObject();
			updatePersonnel.put("comId",jsonObject.getLong("comId"));
			updatePersonnel.put("pid",pId);
			if (param.getInteger("openType")==1 || param.getInteger("openType")==3){
				openType=1;
			}else if (param.getInteger("openType")==0 || param.getInteger("openType")==2){
				openType=0;
			}
			updatePersonnel.put("regionOnline",openType);
			updatePersonnel.put("regionId",reginId);
			Result updatePersonnelResult=humanFeignService.updateStudentByInOut(updatePersonnel);
			resultVo.setCode(200);
			resultVo.setMessage("上传门禁记录成功");
			return resultVo;
		}catch (Exception e){
			resultVo.setCode(2300);
			resultVo.setMessage("系统异常");
			log.info("请求方式:【{}】,异常:【{}】","3.1.保存开门记录",e);
			return resultVo;
		}

	}


	public static void main(String[] args){
		System.out.println(Integer.valueOf(200));
	}
}
